package com.coincalf.web;

import com.coincalf.entity.User;
import com.coincalf.framework.exception.GlobalDefaultException;
import com.coincalf.framework.utils.TokenUtil;
import com.coincalf.service.UserService;
import jnr.ffi.Struct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Slf4j
@Component
public class CommonController {

    public static final String LOGIN_SESSION = "login_servlet_session";

    public static final String MOBILE = "user_mobile";

    public static final String USER_ID = "user_id";

    protected User getUser(HttpServletRequest request) {
        return (User) request.getAttribute(CommonController.LOGIN_SESSION);
    }

    protected String getUserMobile(HttpServletRequest request) {
        return (String) request.getAttribute(CommonController.MOBILE);
    }

    protected Long getUserId(HttpServletRequest request) {
        return Long.parseLong(request.getAttribute(CommonController.USER_ID).toString());
    }

    /*@Autowired
    private UserService userService;

    public Long getUserId(HttpServletRequest request) {
        String token = request.getHeader("TOKEN");
        log.info("token={}", token);
        Map<String, Object> map = TokenUtil.parserToken(token);
        if (map == null) {
            throw new GlobalDefaultException("TOKEN解析失败");
        }
        String username = String.valueOf(map.get("username"));
        User user = userService.selectByPhone(username);
        if (user == null) {
            throw new GlobalDefaultException(2018);
        }
        return user.getId();
    }

    public User getUser(HttpServletRequest request) {
        String token = request.getHeader("TOKEN");
        Map<String, Object> map = TokenUtil.parserToken(token);
        if (map == null) {
            throw new GlobalDefaultException("TOKEN解析失败");
        }
        String username = String.valueOf(map.get("username"));
        User user = userService.selectByPhone(username);
        if (user == null) {
            throw new GlobalDefaultException(2018);
        }
        return user;
    }*/

}
